#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
批量图片转视频工具
使用阿里云DashScope API将文件夹中的图片转换为视频
"""

import os
import sys
import json
from pathlib import Path
from typing import List, Tuple
import time

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(project_root)

from src.processors.i2v_processor import async_call_i2v, wait_for_task, fetch_task_status


def batch_process_images_to_videos(images_dir: str, output_dir: str, resolution: str = "1080P") -> bool:
    """
    批量处理文件夹中的图片并生成视频
    
    Args:
        images_dir (str): 包含图片的目录路径
        output_dir (str): 视频输出目录路径
        resolution (str): 视频分辨率，默认为"1080P"
        
    Returns:
        bool: 处理是否成功
    """
    # 确保目录存在
    images_path = Path(images_dir)
    output_path = Path(output_dir)
    
    if not images_path.exists():
        print(f"错误: 图片目录 {images_dir} 不存在")
        return False
    
    output_path.mkdir(parents=True, exist_ok=True)
    
    # 查找所有图片文件
    image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.tiff']
    image_files = []
    
    for ext in image_extensions:
        image_files.extend(images_path.glob(ext))
    
    if not image_files:
        print(f"在目录 {images_dir} 中未找到图片文件")
        return False
    
    print(f"找到 {len(image_files)} 个图片文件")
    
    # 固定的视频提示词
    prompt = "运镜左右缓慢的晃动，适当扩展图片内容，但是不得出现和原图片内容无关的东西"
    
    # 处理每个图片
    success_count = 0
    for i, image_file in enumerate(image_files):
        print(f"\n处理第 {i+1}/{len(image_files)} 个图片: {image_file.name}")
        
        # 生成输出视频路径
        video_filename = image_file.stem + ".mp4"
        video_path = output_path / video_filename
        
        # 检查是否已存在视频文件
        if video_path.exists():
            print(f"视频文件 {video_filename} 已存在，跳过")
            success_count += 1
            continue
        
        # 调用图片转视频API
        success = process_single_image_to_video(str(image_file), str(video_path), prompt, resolution)
        if success:
            success_count += 1
            print(f"成功生成视频: {video_filename}")
        else:
            print(f"生成视频失败: {image_file.name}")
    
    print(f"\n处理完成: {success_count}/{len(image_files)} 个图片成功生成视频")
    return success_count > 0


def process_single_image_to_video(image_path: str, output_path: str, prompt: str, resolution: str = "1080P") -> bool:
    """
    处理单个图片生成视频
    
    Args:
        image_path (str): 图片文件路径
        output_path (str): 输出视频路径
        prompt (str): 视频生成提示词
        resolution (str): 视频分辨率
        
    Returns:
        bool: 处理是否成功
    """
    try:
        # 构造file://协议的路径
        if os.name == 'nt':  # Windows系统
            image_path = image_path.replace('\\', '/')
        img_url = "file://" + image_path
        
        print(f"开始处理图片: {image_path}")
        print(f"视频描述: {prompt}")
        print(f"分辨率: {resolution}")
        
        # 异步调用图片到视频生成功能
        task_id, error = async_call_i2v(img_url, prompt, resolution)
        if error:
            print(f"调用失败: {error}")
            return False
        
        print(f"任务已提交，任务ID: {task_id}")
        
        # 等待任务完成，轮询状态
        max_wait_time = 300  # 最大等待时间5分钟
        wait_interval = 5    # 轮询间隔5秒
        elapsed_time = 0
        
        while elapsed_time < max_wait_time:
            task_status, video_url, status_error = fetch_task_status(task_id)
            if status_error:
                print(f"获取任务状态失败: {status_error}")
                return False
            
            print(f"任务状态: {task_status}")
            
            if task_status == "SUCCEEDED":
                # 任务成功完成
                if video_url:
                    # 下载视频
                    import requests
                    video_data = requests.get(video_url)
                    if video_data.status_code == 200:
                        with open(output_path, 'wb') as f:
                            f.write(video_data.content)
                        print(f"视频已保存到: {output_path}")
                        return True
                    else:
                        print(f"下载视频失败，状态码: {video_data.status_code}")
                        return False
                else:
                    print("任务成功但未返回视频URL")
                    return False
                    
            elif task_status == "FAILED":
                print("任务执行失败")
                return False
                
            elif task_status == "RUNNING":
                # 任务仍在运行，继续等待
                print(f"任务仍在运行，已等待 {elapsed_time} 秒...")
                time.sleep(wait_interval)
                elapsed_time += wait_interval
            else:
                print(f"未知任务状态: {task_status}")
                time.sleep(wait_interval)
                elapsed_time += wait_interval
        
        print("任务超时未完成")
        return False
        
    except Exception as e:
        print(f"处理图片生成视频时出错: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """
    主函数，提供命令行接口
    """
    if len(sys.argv) < 3:
        print("用法: python batch_image_to_video.py <图片目录> <输出目录> [分辨率]")
        print("示例: python batch_image_to_video.py ./images ./videos 1080P")
        print("支持的分辨率: 480P, 720P, 1080P")
        return
    
    images_dir = sys.argv[1]
    output_dir = sys.argv[2]
    resolution = sys.argv[3] if len(sys.argv) > 3 else "1080P"
    
    success = batch_process_images_to_videos(images_dir, output_dir, resolution)
    if success:
        print("批量处理完成")
        sys.exit(0)
    else:
        print("批量处理失败")
        sys.exit(1)


if __name__ == "__main__":
    main()